import React, { useState, useCallback, useEffect, useMemo } from "react";
import { Form, Row, Col, Button, Input } from "antd";
import { SearchOutlined, ReloadOutlined } from "@ant-design/icons";
import { cloneDeep, debounce } from "lodash";
import Iconfont from "@/components/IconFont";

const SearchItems = React.memo(({ cols, span, form, formWidth, searchFormVisible, defaultStyle, searchGutter, searchWidth, maxCol }) => {
	let width = 138 + searchGutter; // 搜索和重置按钮的默认宽度
	let times = 0;
	return cols.map((col, index) => {
		const SEARCH_ITEM = col.search || {};
		// search.code优先,以便与列表区分
		const CODE = SEARCH_ITEM.code || col.code;
		const SPAN = SEARCH_ITEM.span || span || 3;
		const { group, render, content, formItemProps, hidden } = SEARCH_ITEM;
		// key
		const KEY = (CODE || "key") + "-" + index + "-";
		// 样式
		const WIDTH = (SPAN / BASE_COL) * searchWidth + searchGutter * (SPAN / BASE_COL - 1);
		const style = { width: WIDTH + "px", ...defaultStyle };
		// 计算总宽度
		width = width + WIDTH + searchGutter;
		// 当Col总宽度大于搜索表单的宽度时，并且表单是收起状态时，隐藏多余的搜索项
		if (width > formWidth && searchFormVisible === false && (maxCol ? times > (maxCol - 1) : true)) {
			style.display = "none";
		} else {
			style.display = "block";
			times++;
		}

		/************* 以下渲染搜索项 ******************** */
		if (content) {
			// 通用 col.searchContent : ()=> <Input />
            if(hidden){
                return null
            }
			return (
				<div style={style} key={KEY}>
					<Form.Item name={CODE} {...(formItemProps || {})}>
						{content(form)}
					</Form.Item>
				</div>
			);
		}
		// 只包一层 col 需要在render中写 Form.Item
		if (render) {
			return (
				<div style={style} key={KEY}>
					{render(form, col)}
				</div>
			);
		}

		// 如果 group 是数组
		if (group && Array.isArray(group)) {
			// searchGroup
			const GROUP_ELEMENTS = group.map((__SEARCH_ITEM, childIndex) => {
				// searchCode优先,以便与列表区分
				const __CODE = __SEARCH_ITEM.code;
				const __SPAN = __SEARCH_ITEM.span;
				const { group: __group, render: __render, content: __content, formItemProps: __formItemProps } = __SEARCH_ITEM;
				const __KEY = KEY + "-" + __CODE + "-" + childIndex;
				if (__render) {
					return (
						<Col span={__SPAN} key={__KEY}>
							{__render(form, __SEARCH_ITEM)}
						</Col>
					);
				}
				// searchGroup=>searchContent
				return (
					<Col span={__SPAN} key={__KEY}>
						<Form.Item noStyle={true} {...(__formItemProps || {})} name={__CODE}>
							{__content && __content(form)}
						</Form.Item>
					</Col>
				);
			});
			// col + searchGroup
			return (
				<div style={style} key={KEY}>
					<Form.Item>
						<Input.Group>
							<Row>{GROUP_ELEMENTS}</Row>
						</Input.Group>
					</Form.Item>
				</div>
			);
		}
		return (
			<Col style={style} key={KEY}>
				配置错误
			</Col>
		);
	});
});

function getSortColumns(columns) {
	const filterColumns = columns.filter(e => e.search);
	const sortColumns = filterColumns
		.map((e, index) => {
			const order = e.search.order ?? index + 2;
			const search = {
				...e.search,
				order
			};
			return {
				...e,
				search
			};
		})
		.sort((a, b) => a.search.order - b.search.order);
	return sortColumns;
}
/**
 *
 * @param {*} form
 * @param {*} tableKey
 * @param {*} columns
 * @param {*} onSearchReset
 * @param {*} onSearchReset
 * @param {*} searchWidth 搜索框的默认宽度 210px
 * @param {*} searchGutter  默认间隔 14px
 * @param {*} searchSpan  默认宽度的倍数 以3为基，2倍宽度写6（兼容 24/8 格的写法）
 * @param {*} quickSearch  快捷搜索组件
 * @returns
 */
const BASE_COL = 3;
export default React.memo(
	({
		form,
		tableKey,
		columns,
		beforeReset,
		onSearchReset,
		onSearchFinish,
		onSearchChange,
		searchWidth = 210, ///默认宽度
		searchGutter = 14, //默认间隔
		searchSpan = 3, //默认宽度的倍数 以3为基，2倍宽度写6（兼容 24/8 格的写法）
		quickSearch: QuickSearch,
		searchFormVisible,
		showMoreAction = false,
		getSearchFormVal,
		RefSearchTable,
		rowKey,
		maxCol,
        // hidden = true
	}) => {
		const ComponentName = "SearchForm";
		useEffect(() => {
			// console.warn(`${ComponentName},初始化`);
		}, []);
		const sortColumns = useMemo(() => getSortColumns(columns), [columns]);

		const onReset = useCallback(() => {
			beforeReset && beforeReset();
			form.resetFields();
			onSearchReset && onSearchReset(form.getFieldsValue());
		}, []);

		const onFinish = useCallback(
			val => {
				return onSearchFinish(cloneDeep(val));
			},
			[sortColumns, onSearchFinish]
		);

		const onValuesChange = (changedValues, allValues) => {
			onSearchChange && onSearchChange(cloneDeep(allValues));
		};

		const [id] = useState("form-" + tableKey + "-" + Math.random()); //搜索表单的id
		const [formWidth, setFormWidth] = useState(0); //搜索表单的动态宽度
		/**
		 * @description 监听窗口变化，获取搜索表单的动态宽度
		 */
		const handleResize = useCallback(
			debounce(() => {
				const formElement = document.getElementById(id);
				const width = (formElement && formElement.offsetWidth) || 0;
				setFormWidth(width);
			}, 500),
			[form, searchFormVisible]
		);

		useEffect(() => {
			//初始化时，获取搜索表单的动态宽度
			handleResize();
			// 监听窗口变化
			window.addEventListener("resize", handleResize);
			return () => {
				// 移除监听
				window.removeEventListener("resize", handleResize);
			};
		}, []);
		const defaultStyle = { marginLeft: searchGutter + "px" };

		const collectSelectedRows = async () => {
			const val = getSearchFormVal();
			const values = Object.values(val.search);
			if (values.filter(e => e !== "" && e !== undefined && e !== null).length === 0) {
				return;
			}
			// form.setFieldsValue(val);
			await onSearchFinish(val.search, "pageChange");
			setTimeout(() => {
				RefSearchTable.current.setTableSelect(val.allPagesSelected.map(item => item[rowKey]));
			}, 600);
		};

		const cleanFormValues = () => {
			form.resetFields();
		};

		const renderSearchItems = useMemo(() => {
            // return null
			return (
				<SearchItems
					maxCol={maxCol}
					cols={sortColumns}
					span={searchSpan}
					form={form}
					formWidth={formWidth}
					defaultStyle={defaultStyle}
					searchWidth={searchWidth}
					searchGutter={searchGutter}
					searchFormVisible={searchFormVisible}
				/>
			);
		}, [sortColumns, searchSpan, formWidth, searchSpan, searchFormVisible]);

		return (
			<Form
				id={id}
				className="views-search-form"
				key={tableKey + "SearchForm"}
				form={form}
				layout="horizontal"
				onValuesChange={onValuesChange}
				onFinish={onFinish}
			>
				{renderSearchItems}

				<div style={defaultStyle}>
					{QuickSearch && searchFormVisible && (
						<QuickSearch tableKey={tableKey} searchFormInstance={form} onQuickSearch={onFinish} />
					)}
					<Button
						type="primary"
						icon={<Iconfont type="iconsousuo" style={{ fontSize: 14 }} />}
						htmlType="submit"
						style={{ marginRight: 8 }}
					>
						搜索
					</Button>
					<Button onClick={onReset} className="mb16">
						<ReloadOutlined /> 重置
					</Button>

					{showMoreAction && (
						<>
							<Button onClick={collectSelectedRows} type="link" style={{ marginLeft: 8, border: "none" }}>
								展示已选商品
							</Button>
							<Button onClick={cleanFormValues} type="link" style={{ marginLeft: 8, border: "none" }}>
								清空已选条件
							</Button>
						</>
					)}
				</div>
			</Form>
		);
	}
);
